﻿using AutoUpdaterDotNET;
using CommonServiceLocator;
using GalaSoft.MvvmLight.Views;

using OfficeHelper.Help;
using OfficeHelper.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Windows;
using System.Windows.Interop;

namespace OfficeHelper
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow 
    {
             

        public MainWindow()
        {
            InitializeComponent();
            CheckUpdate();
            //Init();
        }

        /// <summary>
        /// 检查更新
        /// </summary>
        private  void CheckUpdate()
        {
            //AutoUpdater.ReportErrors = true;
            AutoUpdater.ShowSkipButton = false;//不显示忽略按钮
            AutoUpdater.ShowRemindLaterButton = false;
            AutoUpdater.Start("https://gitee.com/chenhome/OfficeHelper/raw/master/autoupdate.xml?ww=" + DateTime.Now.ToShortDateString());
        }

        private CompositionContainer _container;
        private void Init()
        {
            //设置目录，让引擎能自动去发现新的扩展
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory + "plugin\\"));

            //创建一个容器，相当于是生产车间
            _container = new CompositionContainer(catalog);

            //调用车间的ComposeParts把各个部件组合到一起
            try
            {
                this._container.ComposeParts(this);//这里只需要传入当前应用程序实例就可以了，其它部分会自动发现并组装
            }
            catch (CompositionException compositionException)
            {
                Console.WriteLine(compositionException.ToString());
            }
        }

        private void Button_Click_Theme(object sender, RoutedEventArgs e)
        {
            WindowTheme win = new WindowTheme()
            {
                Owner = this
            };
            win.ShowDialog();
        }

        private void WindowBase_Loaded(object sender, RoutedEventArgs e)
        {
            //快捷键注册
            HotKeySettingsManager.Instance.RegisterGlobalHotKeyEvent += Instance_RegisterGlobalHotKeyEvent;
        }


        private bool Instance_RegisterGlobalHotKeyEvent(System.Collections.ObjectModel.ObservableCollection<HotKeyModel> hotKeyModelList)
        {
            return InitHotKey(hotKeyModelList);
        }


        /// <summary>
        /// WPF窗体的资源初始化完成，并且可以通过WindowInteropHelper获得该窗体的句柄用来与Win32交互后调用
        /// </summary>
        /// <param name="e"></param>
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            // 获取窗体句柄
            m_Hwnd = new WindowInteropHelper(this).Handle;
            HwndSource hWndSource = HwndSource.FromHwnd(m_Hwnd);
            // 添加处理程序
            if (hWndSource != null) hWndSource.AddHook(WndProc);
        }

        /// <summary>
        /// 窗体回调函数，接收所有窗体消息的事件处理函数
        /// </summary>
        /// <param name="hWnd">窗口句柄</param>
        /// <param name="msg">消息</param>
        /// <param name="wideParam">附加参数1</param>
        /// <param name="longParam">附加参数2</param>
        /// <param name="handled">是否处理</param>
        /// <returns>返回句柄</returns>
        private IntPtr WndProc(IntPtr hWnd, int msg, IntPtr wideParam, IntPtr longParam, ref bool handled)
        {
            var hotkeySetting = new EHotKeySetting();
            switch (msg)
            {
                case HotKeyManager.WM_HOTKEY:
                    int sid = wideParam.ToInt32();
                    if (sid == m_HotKeySettings[EHotKeySetting.Hidden])
                    {

                        if (this.WindowState == WindowState.Minimized)
                        {
                            this.WindowState = WindowState.Normal;
                            this.Activate();
                        }
                        else
                        {
                            //判断是否在最前
                            if (this.IsActive)
                            {
                                this.WindowState = WindowState.Minimized;
                            }
                            else
                            {
                                this.Activate();
                            }

                        }

                        break;

                        //TODO 执行全屏操作
                    }
                    //else if (sid == m_HotKeySettings[EHotKeySetting.截图])
                    //{
                    //    hotkeySetting = EHotKeySetting.截图;
                    //    //TODO 执行截图操作
                    //}
                    //else if (sid == m_HotKeySettings[EHotKeySetting.播放])
                    //{
                    //    hotkeySetting = EHotKeySetting.播放;
                    //    //TODO ......
                    //}
                    //else if (sid == m_HotKeySettings[EHotKeySetting.前进])
                    //{
                    //    hotkeySetting = EHotKeySetting.前进;
                    //}
                    //else if (sid == m_HotKeySettings[EHotKeySetting.后退])
                    //{
                    //    hotkeySetting = EHotKeySetting.后退;
                    //}
                    //else if (sid == m_HotKeySettings[EHotKeySetting.保存])
                    //{
                    //    hotkeySetting = EHotKeySetting.保存;
                    //}
                    //else if (sid == m_HotKeySettings[EHotKeySetting.打开])
                    //{
                    //    hotkeySetting = EHotKeySetting.打开;
                    //}
                    //else if (sid == m_HotKeySettings[EHotKeySetting.新建])
                    //{
                    //    hotkeySetting = EHotKeySetting.新建;
                    //}
                    //else if (sid == m_HotKeySettings[EHotKeySetting.删除])
                    //{
                    //    hotkeySetting = EHotKeySetting.删除;
                    //}
                    MessageBox.Show(string.Format("触发【{0}】快捷键", hotkeySetting));
                    handled = true;
                    break;
            }
            return IntPtr.Zero;
        }

        /// <summary>
        /// 所有控件初始化完成后调用
        /// </summary>
        /// <param name="e"></param>
        protected override void OnContentRendered(EventArgs e)
        {
            base.OnContentRendered(e);
            // 注册热键
            InitHotKey();
        }


        /// <summary>
        /// 当前窗口句柄
        /// </summary>
        private IntPtr m_Hwnd = new IntPtr();
        /// <summary>
        /// 记录快捷键注册项的唯一标识符
        /// </summary>
        private Dictionary<EHotKeySetting, int> m_HotKeySettings = new Dictionary<EHotKeySetting, int>();

        private bool InitHotKey(ObservableCollection<HotKeyModel> hotKeyModelList=null)
        {
            var list = hotKeyModelList ?? HotKeySettingsManager.Instance.LoadDefaultHotKey();
            // 注册全局快捷键
            string failList = HotKeyHelper.RegisterGlobalHotKey(list, m_Hwnd, out m_HotKeySettings);
            if (string.IsNullOrEmpty(failList))
                return true;
            MessageBoxResult mbResult = MessageBox.Show(string.Format("无法注册下列快捷键\n\r{0}是否要改变这些快捷键？", failList), "提示", MessageBoxButton.YesNo);
            //弹出热键设置窗体
           //var win = HotKeySettingsWindow.CreateInstance();
            if (mbResult == MessageBoxResult.Yes)
            {
                var navigationService = ServiceLocator.Current.GetInstance<INavigationService>();
                navigationService.NavigateTo("Settings");
                //if (!win.IsVisible)
                //{
                //    win.ShowDialog();
                //}
                //else
                //{
                //    win.Activate();
                //}
                return false;
            }
            return true;
        }
        /// <summary>
        /// 窗体状态更改时 任务栏相应的 隐藏/显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WindowBase_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState == WindowState.Minimized )
            {
                this.ShowInTaskbar = false;
            }
            else
            {
                this.ShowInTaskbar = true;
            }
        }
        /// <summary>
        /// 关闭时取消隐藏当前窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WindowBase_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (SettingsModel.Default.IsCloseMinimized)
            {
                e.Cancel = true;
                this.WindowState = WindowState.Minimized;
            }
        }

        /// <summary>
        /// 窗口关闭 保存参数设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WindowBase_Closed(object sender, EventArgs e)
        {
            SettingsModel.Default.Save();
        }

        //private void WindowBase_Loaded(object sender, RoutedEventArgs e)
        //{
        //    foreach (IPlugin plugin in plugins)
        //    {
        //        btnok.Content = plugin.Text;
        //        btnok.Click += (s, arg) => { plugin.Do(); };
        //    }
        //}
    }
}
